import { DatePicker, Input, Table, message, Select, Form, Space } from 'antd';
import Button from 'antd/es/button';
import { ColumnsType } from 'antd/es/table/interface';
import { FetchDataParam, FetchDataResponse, PageSelect } from 'components/UILibrary/pageSelect';
import moment from 'moment';
import React from 'react';

import {
  ColInfoResponse,
  GetCallRecordParams,
  HandleColInfo,
  TaskCallRecordInfo,
} from 'admin/schema/Task';
import {
  getCallRecordList,
  createDownloadTask,
  getCallRecordCol,
  modifyCallRecordCol,
} from 'admin/servers/servers';

import { clearNull, getTableIndex } from 'utils/tools';
import { CustomCol } from '../../components/CustomCol';
import { checkPermission } from 'permission/Index';
import {
  callStatusOption,
  getCallStatusName,
  getCallTypeOption,
  getHangupDirectName,
  getSoundTypeOption,
  getTaskFlowTypeName,
  getTransferManualStatusName,
  getUserIntentionOption,
} from '../../components/TaskTool';
import { CallRecordDetailDrawer } from 'components/CallRecordDetailDrawer';
import { DownloadTaskInfo } from 'admin/schema/DownloadTask';

interface CallRecordProp {
  taskId: number;
  // 任务重呼轮次
  repeatTimes: number;
}

interface CallRecordState extends CallRecordProp {
  /**查询条件*/
  searchForm: any;
  // /**
  //  * 搜索条件开始时间
  //  * 形如： 2020-11-30 13:00
  //  */
  // beginTime: string;
  // /**
  //  * 搜索条件结束时间
  //  * 形如： 2020-11-30 13:00
  //  */
  // endTime: string;
  // calledNumber: string;
  // calledName: string;
  // callStatus?: number[];
  // /**搜索条件：重呼轮次*/
  // repeatCallTimes?: number;
  /** table列头 */
  tableColumns: ColumnsType<TaskCallRecordInfo>;
  /** 定制列应用的结构 */
  customCol: HandleColInfo[];
  tableData: TaskCallRecordInfo[];
  // 分页相关数据
  pageInfo: {
    pageTotal: number;
    pageNum: number;
    pageSize: number;
  };
  tableLoading: boolean;
  downloadTaskId?: number;
  fileName?: string;
  fileUrl?: string;
}

export class CallRecord extends React.Component<CallRecordProp, CallRecordState> {
  /**记录详情 */
  private callRecordRef: React.RefObject<CallRecordDetailDrawer>;
  /**定制列 */
  private customColRef: React.RefObject<CustomCol>;
  /**通话结果 */
  private statusSelectRef: React.RefObject<PageSelect>;

  private repeatOptions: any;
  constructor(arg: CallRecordProp) {
    super(arg);
    this.callRecordRef = React.createRef();
    this.customColRef = React.createRef();
    this.statusSelectRef = React.createRef();

    this.repeatOptions = [];
    this.state = {
      ...arg,
      searchForm: {} as any,
      // beginTime: '',
      // endTime: '',
      // calledNumber: '',
      // calledName: '',
      // callStatus: undefined,
      tableData: [],
      tableLoading: false,
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      customCol: [],
      tableColumns: [],
      // repeatCallTimes: undefined,
    };
  }

  componentDidMount() {
    this.fetchCol();
    this.fetchList();
    this.repeatOptions = this.initRepeatOptions(this.props.repeatTimes);
    this.statusSelectRef.current?.selectAll();
  }
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }
  /**
   *获取重呼次数下拉选项列表
   * @param {number} max 最大数
   * @return {*}
   */
  private initRepeatOptions(max: number) {
    const arr = [];
    for (let i = 0; i <= max; i++) {
      arr.push({
        value: i,
      });
    }
    return arr;
  }
  /* 自定义-列渲染-【通话记录定制列】 */
  private renderTableCols(item: any) {
    const obj = {
      title: item.desc,
      key: item.columnName,
      dataIndex: item.columnName,
      ellipsis: true,
      render: (text: any, record: TaskCallRecordInfo, index: number) => {
        return text;
      },
    };
    // 前端显示（特殊列-处理）
    switch (item.columnName) {
      case 'callStatus':
        obj.render = text => getCallStatusName(text);
        break;
      case 'callType':
        obj.render = text => getCallTypeOption(text);
        break;
      case 'soundType':
        obj.render = text => getSoundTypeOption(text);
        break;
      case 'hangupDirect':
        obj.render = text => getHangupDirectName(text);
        break;
      case 'transferManualStatus':
        obj.render = text => getTransferManualStatusName(text);
        break;
      case 'flowType':
        obj.render = text => getTaskFlowTypeName(text);
        break;
      case 'userIntentionDegree':
        obj.render = text => getUserIntentionOption(text);
        break;
      default:
        break;
    }
    return obj;
  }

  /**获取呼叫结果-下拉列表数据-前端拼接，无后端接口返回 */
  private fetchCallResultOptions(arg: FetchDataParam): FetchDataResponse {
    return Promise.resolve({
      data: callStatusOption,
      total: callStatusOption.length,
    });
  }
  /**
   * 展开通话记录详情
   */
  private showDetail(index: number, record: TaskCallRecordInfo) {
    const { pageInfo, searchForm } = this.state;
    const { pageNum, pageSize, pageTotal } = pageInfo;
    const searchParms = {
      ...searchForm,
      pageTotal,
      pageNo: (pageNum - 1) * pageSize + (index + 1), // 根据列表计算当前条位置
      pageSize: 1, // 按每条1页展示
    };
    this.callRecordRef.current?.show(searchParms, record);
  }

  /**
   * 查询table数据
   */
  private async fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { pageInfo, searchForm } = this.state;
    try {
      const params: GetCallRecordParams = {
        ...searchForm,
        pageNo: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
      };
      const { count = 0, data = [] } = await this.fetchCallRecord(clearNull(params));
      pageInfo.pageTotal = count;
      this.setState({
        tableData: data,
        pageInfo,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      tableLoading: false,
    });
  }

  /**请求列表数据-单独，方便详情页调用 */
  private async fetchCallRecord(params: GetCallRecordParams) {
    const { taskId } = this.state;
    const res = await getCallRecordList(taskId, clearNull(params));
    return res;
  }

  /**
   * 获取列头信息
   */
  private async fetchCol() {
    try {
      const { data } = await getCallRecordCol();
      const { custom_cols, table_columns } = this.renderCol(data);
      this.setState({
        customCol: custom_cols,
        tableColumns: table_columns,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }

  private renderCol(originData: ColInfoResponse[]) {
    /**定制列信息 */
    const custom_cols: HandleColInfo[] = [];
    /**表格列数据 */
    const table_cols: ColumnsType<TaskCallRecordInfo> = [];
    // 遍历列数据
    const arr = ['转接人工状态', '转接人工等待时长', '人工介入时长'];
    originData
      .filter(({ desc }) => !arr.includes(desc))
      .forEach((item, index) => {
        // console.log("原始-列信息-", item);
        item.desc = item.desc ? item.desc : '列-' + item.columnName;
        // 定制列，存储所有列
        custom_cols.push({
          title: item.desc,
          key: item.columnName,
          switch: item.switch,
        });
        // table，只查找为on的列，存入table列展示
        if (item.switch === 'on') {
          const obj = this.renderTableCols(item);
          table_cols.push(obj);
        }
      });
    /**表格第一列：序号列 */
    const index_col: any = {
      title: '序号',
      key: 'index',
      dataIndex: 'index',
      fixed: 'left',
      width: 70,
      render: (text: any, record: TaskCallRecordInfo, index: number) =>
        getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
    };
    /**表格最后一列：操作列 */
    const operation_col = {
      title: '操作',
      key: 'opearation',
      fixed: 'right',
      width: 80,
      render: (text: any, record: TaskCallRecordInfo, index: number) => {
        return (
          <Button
            type="link"
            onClick={() => {
              this.showDetail(index, record);
            }}
          >
            详情
          </Button>
        );
      },
    };
    /**数据源：表格列;switch为on，包含，序号，操作列 */
    const table_columns: any = [index_col, ...table_cols, operation_col];
    console.log('table_columns', table_columns);
    return {
      custom_cols,
      table_columns,
    };
  }

  /**
   * 查询操作，提交查询表单
   */
  handleSearch = ({ calledNumber, calledName, repeatCallTimes, callStatus, rangeTime }: any) => {
    // 特殊字段预处理
    const status =
      callStatus.length === 0 || callStatus.length === 23
        ? undefined
        : callStatus.map((item: { value: any }) => item.value);
    const beginTime = rangeTime ? rangeTime[0].format('YYYY-MM-DD HH:mm:ss') : undefined;
    const endTime = rangeTime ? rangeTime[1]?.format('YYYY-MM-DD HH:mm:ss') : undefined;
    this.setState(
      {
        searchForm: {
          calledNumber,
          calledName,
          repeatCallTimes,
          callStatus: status,
          beginTime,
          endTime,
        },
      },
      () => {
        this.jumpPage(1);
      }
    );
  };
  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }

  /**
   * 打开定制列对话框
   */
  private handleColumn(): void {
    this.customColRef.current?.show();
    this.customColRef.current?.setCol(this.state.customCol);
  }

  /**创建下载任务*/
  private async handleExport(): Promise<void> {
    const { taskId, searchForm } = this.state;
    const params: DownloadTaskInfo = clearNull({
      taskId: taskId,
      ...searchForm,
    });

    try {
      await createDownloadTask(params);
      // 创建下载任务
      message.warning('数据正在准备中，请稍候到下载管理中下载');
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }

  render() {
    const {
      tableColumns,
      tableData,
      tableLoading,
      pageInfo: { pageNum, pageSize, pageTotal },
    } = this.state;

    const { callRecordRef, customColRef, statusSelectRef, repeatOptions } = this;

    return (
      <>
        <div className="mgr-header detail-callrecord-header">
          <Form className="search-form" layout="inline" onFinish={this.handleSearch}>
            <Form.Item
              label=""
              name="calledNumber"
              getValueFromEvent={event => {
                return event.target.value.replace(/[^0-9]+/g, '');
              }}
            >
              <Input maxLength={20} placeholder="请输入被叫号码" allowClear />
            </Form.Item>
            <Form.Item
              label=""
              name="calledName"
              getValueFromEvent={event => {
                return event.target.value.replace(/\s+/g, '');
              }}
            >
              <Input allowClear placeholder="请输入姓名" />
            </Form.Item>
            <Form.Item label="" name="callStatus">
              <PageSelect
                ref={statusSelectRef}
                fetchData={this.fetchCallResultOptions}
                multiChoice={true}
                pageSize={10000}
                showCheckBox={true}
                showOutsideItem={false}
              />
            </Form.Item>
            <Form.Item label="" name="rangeTime">
              <DatePicker.RangePicker
                format="YYYY-MM-DD HH:mm:ss"
                showTime
                ranges={{
                  今天: [moment().startOf('day'), moment().endOf('day')],
                  本周: [moment().startOf('week'), moment().endOf('week')],
                  本月: [moment().startOf('month'), moment().endOf('month')],
                }}
              />
            </Form.Item>
            <Form.Item label="" name="repeatCallTimes">
              <Select allowClear placeholder="重呼轮次" options={repeatOptions} />
            </Form.Item>
            <Space>
              <Button className="callrecord-searchbtn" type="primary" htmlType="submit">
                搜索
              </Button>
              <Button
                className="callrecord-customcol"
                type="primary"
                onClick={() => {
                  this.handleColumn();
                }}
              >
                定制列
              </Button>
              {checkPermission('/downloadmanage/export') && (
                <Button
                  className="callrecord-export"
                  type="primary"
                  onClick={() => {
                    this.handleExport();
                  }}
                >
                  导出
                </Button>
              )}
            </Space>
          </Form>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            dataSource={tableData}
            scroll={{ x: 'max-content' }}
            columns={tableColumns}
            rowKey="callRecordId"
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <CallRecordDetailDrawer ref={callRecordRef} fetchRecord={this.fetchCallRecord.bind(this)} />
        <CustomCol
          callback={res => {
            modifyCallRecordCol(res)
              .then(response => {
                message.success('编辑成功');
                this.fetchCol();
              })
              .catch(error => {
                console.error(`系统异常: ${JSON.stringify(error)}`);
              });
          }}
          ref={customColRef}
        />
      </>
    );
  }
}
